// $_Auto_Import_start_
import './router/demo'
import './router/message'
import './router/upload'
// $_Auto_Import_end_


import router from '@/middleware/router'
import Koa from 'koa'
import KoaBody from 'koa-body'
import koaMount from 'koa-mount'
import KoaStatic from 'koa-static'
import KoaCors from 'koa2-cors'
import path from 'path'

const app = new Koa()
const PORT = 8888


app.use(KoaCors())

app.use(
  KoaBody({
    multipart: true,    //解析多个文件
    formidable: {
      maxFileSize: 100 * 1024 * 1024,    // 设置上传文件大小最大限制，默认2M
      //uploadDir: 可以填写一个路径，不填写默认为 os.tmpDir()
    }
  })
)
app.use(KoaStatic(path.resolve(__dirname, "../public")))


app.use(koaMount('/upload', KoaStatic(path.resolve(__dirname, "./upload"))))


app.use(router.routes()).use(router.allowedMethods())

const startServer = (port = 7777) => {
  app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`)
  }).on('error', (err: any) => {
    if (err.code === 'EADDRINUSE') {
      console.log(`端口 ${port} 被占用，尝试端口 ${port + 1}`)
      startServer(port + 1)
    } else {
      console.error('服务器启动错误:', err)
    }
  })
}

startServer(PORT)